package com.analysis;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.analysis.databinding.AnalysisBinding;
import com.common.api.RouterPath;
import com.common.pojo.analysis.CategoryPojo;
import com.common.pojo.analysis.MonthlyStatisticsPojo;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.bkkp.AnalysisPojo;
import com.common.pojo.detail.Record;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;

@Route(path = RouterPath.ANALYSIS_MAIN)
public class AnalysisFragment extends Fragment {

    private AnalysisBinding analysisBinding;//视图绑定，避免使用R.id.xx有空的风险

    private ExecutorService executorService;

    private PieChart expenseCategoryChart;
    private BarChart monthlyTrendChart;
    private TextView totalIncomeTextView;
    private TextView totalExpenseTextView;
    private TextView balanceTextView;
    private UserInfoPojo userInfo;
    private Spinner yearSpinner;
    private Spinner categorySpinner;
    private Integer currentYear;
    private boolean isFirstLoadYear = true; // 标记是否为首次初始化
    private boolean isFirstLoadType = true; // 标记是否为首次初始化

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        executorService = Executors.newSingleThreadExecutor();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        analysisBinding = AnalysisBinding.inflate(inflater, container, false);

        expenseCategoryChart = analysisBinding.expenseCategoryChart;
        monthlyTrendChart = analysisBinding.monthlyTrendChart;
        totalIncomeTextView = analysisBinding.totalIncomeTextView;
        totalExpenseTextView = analysisBinding.totalExpenseTextView;
        balanceTextView = analysisBinding.balanceTextView;
        userInfo = JSONObject.parseObject(Constants.userInfo, UserInfoPojo.class);

        setupCharts();
        Calendar calendar = Calendar.getInstance();
        //获取到今年
        currentYear = calendar.get(Calendar.YEAR);
        // 加载统计数据，默认初始查询当前数据
        loadStatistics(currentYear.toString());

        yearSpinner = analysisBinding.yearSpinner;
        categorySpinner = analysisBinding.categorySpinner;
        //查询年份
        searYear();
        categorySpinnerInit();


        return analysisBinding.getRoot();
    }

    private void categorySpinnerInit() {
        List<String> list = new ArrayList<>();
        list.add("收入");
        list.add("支出");
        // 创建 ArrayAdapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                requireActivity(),
                android.R.layout.simple_spinner_item, // 默认布局
                list
        );

        // 设置下拉列表的样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 将适配器应用到 Spinner
        categorySpinner.setAdapter(adapter);
        isFirstLoadType = true;

        // 设置选中事件监听
        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedMonth = parent.getItemAtPosition(position).toString();
                Object selectedItem = yearSpinner.getSelectedItem();
                if (isFirstLoadType) { // 首次加载时跳过逻辑
                    isFirstLoadType = false; // 关闭标记
                    return;
                }
                if (selectedItem != null) {
                    int type = 2;
                    if ("收入".equalsIgnoreCase(selectedMonth)) {
                        type = 1;
                    }
                    searchCategory(selectedItem.toString(), type);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择任何项的处理
            }
        });
        categorySpinner.setSelection(1);
    }

    //查询目前用户数据所有年份
    private void searYear() {
        OkHttpUtils.get().url(ConstantsUrl.searchYearUrl)
                .addParams("userId", userInfo.getId().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    List<String> list = JSONObject.parseArray(result.getData().toString(), String.class);
                    requireActivity().runOnUiThread(() -> {
                        yearSpinnerMethod(list);
                    });
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    private void yearSpinnerMethod(List<String> list) {
        if (isAdded() && getView() != null) {
            list.remove(currentYear.toString());
            list.add(currentYear.toString());
            // 创建 ArrayAdapter
            ArrayAdapter<String> adapter = new ArrayAdapter<>(
                    requireActivity(),
                    android.R.layout.simple_spinner_item, // 默认布局
                    list
            );

            // 设置下拉列表的样式
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // 将适配器应用到 Spinner
            yearSpinner.setAdapter(adapter);
            isFirstLoadYear = true;

            // 设置选中事件监听
            yearSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (isFirstLoadYear) { // 首次加载时跳过逻辑
                        isFirstLoadYear = false; // 关闭标记
                        return;
                    }
                    String selectedMonth = parent.getItemAtPosition(position).toString();
                    loadStatistics(selectedMonth);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // 未选择任何项的处理
                }
            });
            yearSpinner.setSelection(list.indexOf(currentYear.toString()));
        }
    }

    private void setupCharts() {
        // 设置支出分类饼图
        expenseCategoryChart.setUsePercentValues(true);
        expenseCategoryChart.getDescription().setEnabled(false);
        expenseCategoryChart.setExtraOffsets(5, 10, 5, 5);
        expenseCategoryChart.setDragDecelerationFrictionCoef(0.95f);
        expenseCategoryChart.setDrawHoleEnabled(true);
        expenseCategoryChart.setHoleColor(Color.WHITE);
        expenseCategoryChart.setTransparentCircleColor(Color.WHITE);
        expenseCategoryChart.setTransparentCircleAlpha(110);
        expenseCategoryChart.setHoleRadius(58f);
        expenseCategoryChart.setTransparentCircleRadius(61f);
        expenseCategoryChart.setDrawCenterText(true);
        expenseCategoryChart.setRotationAngle(0);
        expenseCategoryChart.setRotationEnabled(true);
        expenseCategoryChart.setHighlightPerTapEnabled(true);

        // 设置月度趋势柱状图
        monthlyTrendChart.getDescription().setEnabled(false);
        monthlyTrendChart.setMaxVisibleValueCount(60);
        monthlyTrendChart.setPinchZoom(false);
        monthlyTrendChart.setDrawBarShadow(false);
        monthlyTrendChart.setDrawGridBackground(false);

        XAxis xAxis = monthlyTrendChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(getMonthLabels()));

        monthlyTrendChart.getAxisLeft().setDrawGridLines(true);
        monthlyTrendChart.getAxisRight().setEnabled(false);
    }

    private void loadStatistics(String currentYear) {
        executorService.execute(() -> {

            //查询年度统计,总收入、总支出、结余
            searchYear(currentYear);
            //通过类别查询统计
            searchCategory(currentYear, 2);
            //按月份查询收支情况统计
            searchMonth(currentYear);

        });
    }

    //查询年度统计
    private void searchYear(String currentYear) {
        OkHttpUtils.get().url(ConstantsUrl.yearAnlysisUrl)
                .addParams("userId", userInfo.getId().toString())
                .addParams("year", currentYear)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    AnalysisPojo analysisPojo = JSONObject.parseObject(result.getData().toString(), AnalysisPojo.class);
                    requireActivity().runOnUiThread(() -> {
                        //总的支出收入结余
                        updateSummaryInfo(analysisPojo);
                    });
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    //通过类别查询统计
    private void searchCategory(String currentYear, Integer type) {
        OkHttpUtils.get().url(ConstantsUrl.categoryAnlysisUrl)
                .addParams("userId", userInfo.getId().toString())
                .addParams("year", currentYear)
                .addParams("type", type.toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    List<CategoryPojo> categoryPojos = JSONObject.parseArray(result.getData().toString(), CategoryPojo.class);
                    requireActivity().runOnUiThread(() -> {
                        //分类统计
                        updateExpenseCategoryChart(categoryPojos);
                    });
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    //通过类别查询统计
    private void searchMonth(String currentYear) {
        OkHttpUtils.get().url(ConstantsUrl.monthAnlysisUrl)
                .addParams("userId", userInfo.getId().toString())
                .addParams("year", currentYear)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    List<MonthlyStatisticsPojo> monthlyStatisticsPojos = JSONObject.parseArray(result.getData().toString(), MonthlyStatisticsPojo.class);
                    requireActivity().runOnUiThread(() -> {
                        // 按月份统计收支
                        double[] monthlyIncomes = new double[12];
                        double[] monthlyExpenses = new double[12];
                        for (MonthlyStatisticsPojo msp : monthlyStatisticsPojos) {
                            if (msp.getType() == 1) {
                                //收入
                                monthlyIncomes[msp.getMonth() - 1] = msp.getTotalAmount();
                            } else {
                                //支出
                                monthlyExpenses[msp.getMonth() - 1] = msp.getTotalAmount();
                            }
                        }
                        //按月份
                        updateMonthlyTrendChart(monthlyIncomes, monthlyExpenses);

                    });
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    private void updateSummaryInfo(AnalysisPojo analysisPojo) {
        if (isAdded() && getView() != null) {
            totalIncomeTextView.setText(String.format("¥%.2f", analysisPojo.getIncome()));
            totalExpenseTextView.setText(String.format("¥%.2f", analysisPojo.getNsume()));
            balanceTextView.setTextColor(analysisPojo.getSurplus() >= 0
                    ? Color.parseColor("#2196F3")
                    : Color.parseColor("#E12F2F"));
            balanceTextView.setText(String.format("¥%.2f", analysisPojo.getSurplus()));
        }

    }

    private void updateExpenseCategoryChart(List<CategoryPojo> categoryPojos) {
        if (isAdded() && getView() != null) {
            List<PieEntry> entries = new ArrayList<>();
            for (CategoryPojo categoryPojo : categoryPojos) {
                entries.add(new PieEntry(categoryPojo.getTotalAmount(), categoryPojo.getCategory()));
            }

            PieDataSet dataSet = new PieDataSet(entries, "支出分类");
            dataSet.setSliceSpace(3f);
            dataSet.setSelectionShift(5f);
            dataSet.setColors(ColorTemplate.MATERIAL_COLORS);

            PieData data = new PieData(dataSet);
            data.setValueTextSize(11f);
            data.setValueTextColor(Color.WHITE);

            expenseCategoryChart.setData(data);
            expenseCategoryChart.highlightValues(null);
            expenseCategoryChart.invalidate();
        }
    }

    private void updateMonthlyTrendChart(double[] monthlyIncomes, double[] monthlyExpenses) {
        if (isAdded() && getView() != null) {
            List<BarEntry> incomeEntries = new ArrayList<>();
            List<BarEntry> expenseEntries = new ArrayList<>();

            for (int i = 0; i < 12; i++) {
                incomeEntries.add(new BarEntry(i, (float) monthlyIncomes[i]));
                expenseEntries.add(new BarEntry(i, (float) monthlyExpenses[i]));
            }

            BarDataSet incomeDataSet = new BarDataSet(incomeEntries, "收入");
            incomeDataSet.setColor(Color.GREEN);
            BarDataSet expenseDataSet = new BarDataSet(expenseEntries, "支出");
            expenseDataSet.setColor(Color.RED);

            BarData data = new BarData(incomeDataSet, expenseDataSet);
            data.setBarWidth(0.35f);

            monthlyTrendChart.setData(data);
            monthlyTrendChart.groupBars(-0.35f, 0.4f, 0.02f);
            monthlyTrendChart.invalidate();
        }
    }

    private String[] getMonthLabels() {
        return new String[]{"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"};
    }

    private void showToast(String content) {
        requireActivity().runOnUiThread(() -> {
            if (isAdded() && getView() != null) { // 双重校验（可选）
                Toast.makeText(requireContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (executorService != null) {
            executorService.shutdown();
        }
    }

}